package personal.jinhui.paprika.utils;

import personal.jinhui.paprika.PaprikaService;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.widget.Toast;

import personal.jinhui.paprika.R;

/**
 * Manage broadcast disconnect intent.
 */
public class PaprikaBroadcastReceiver extends BroadcastReceiver {

	/** Broadcast intent type. */
	public static final String Paprika_CONNECTION_CLOSED = "PaprikaConnectionClosed";

	/**
	 * constructor.
	 */
	public PaprikaBroadcastReceiver() {
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onReceive(final Context context, final Intent intent) {
		String intentAction = intent.getAction();
		if (intentAction.equals(Paprika_CONNECTION_CLOSED)) {
			CharSequence message = intent.getCharSequenceExtra("message");
			Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
			if (context instanceof Activity) {
				Activity act = (Activity) context;
				act.finish();
				// The service will be unbinded in the destroy of the activity.
			}
		} else if (intentAction.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
			if (intent.getBooleanExtra(
					ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {
				Toast.makeText(
						context,
						context.getString(R.string.PaprikaBroadcastReceiverDisconnect),
						Toast.LENGTH_SHORT).show();
				context.stopService(new Intent(context, PaprikaService.class));
			}
		}
	}
}
